/**
 * FormItemInclude.java
 * Copyright (C) 2009 Jose Mauro da Silva Sandy
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

/*
 * FormItemInclude.java
 *
 * Created on 10/05/2009, 00:21:15
 */

package frames;

import java.text.*;
import javax.swing.JOptionPane;
import negocio.notas.*;
import negocio.produto.*;
import utils.ErrorMessage;

/**
 *
 * @author jmsandy
 */
public class FormItemInclude extends javax.swing.JDialog {

    //<editor-fold defaultstate="collapsed" desc="FIELDS">
    private Item item        = null;
    private DecimalFormat df = new DecimalFormat("#,##0.00");
    private Produto produto  = null;
    private int situacao;
    private int modo;
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Constants">
    public static final int K_FORM_NOTA      = 1;
    public static final int K_FORM_ORCAMENTO = 2;
    public static final int K_FORM_EXIBICAO  = 3;
    public static final int K_FORM_CADASTRO  = 4;
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Acessores">
    public Item getItem(){
        return item; }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Constructors">
    /** Creates new form FormItemInclude */
    public FormItemInclude() {
        initComponents();
    }
    public FormItemInclude(Item item, int situacao, int modo){
        initComponents();
        this.item = item;
        this.situacao = situacao;
        this.modo = modo;
        initializeMyComponents();
    }
    //</editor-fold>

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FormItemInclude().setVisible(true);
            }
        });
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lbCodigo = new javax.swing.JLabel();
        textCodigo = new javax.swing.JTextField();
        lbDescricao = new javax.swing.JLabel();
        textDescricao = new javax.swing.JTextField();
        lbQuantidade = new javax.swing.JLabel();
        textQuantidade = new javax.swing.JTextField();
        lbUnidade = new javax.swing.JLabel();
        cbUnidade = new javax.swing.JComboBox();
        lbValUnit = new javax.swing.JLabel();
        textValUnit = new javax.swing.JTextField();
        lbFatorConversao = new javax.swing.JLabel();
        textFatorConv = new javax.swing.JTextField();
        lbValTotal = new javax.swing.JLabel();
        textValorTotal = new javax.swing.JTextField();
        panelBotao = new javax.swing.JPanel();
        btnConfirmar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();

        setTitle("Item");
        setName("formInclude"); // NOI18N
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        lbCodigo.setFont(new java.awt.Font("SansSerif", 0, 12));
        lbCodigo.setText("Código");

        textCodigo.setBackground(java.awt.Color.white);
        textCodigo.setFont(new java.awt.Font("SansSerif", 0, 12));
        textCodigo.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        textCodigo.setPreferredSize(new java.awt.Dimension(10, 26));
        textCodigo.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                textCodigoFocusLost(evt);
            }
        });
        textCodigo.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                textCodigoKeyPressed(evt);
            }
        });

        lbDescricao.setFont(new java.awt.Font("SansSerif", 0, 12));
        lbDescricao.setText("Descrição");

        textDescricao.setBackground(java.awt.Color.white);
        textDescricao.setEditable(false);
        textDescricao.setFont(new java.awt.Font("SansSerif", 0, 12));
        textDescricao.setPreferredSize(new java.awt.Dimension(10, 26));

        lbQuantidade.setFont(new java.awt.Font("SansSerif", 0, 12));
        lbQuantidade.setText("Quantidade");

        textQuantidade.setBackground(java.awt.Color.white);
        textQuantidade.setEditable(false);
        textQuantidade.setFont(new java.awt.Font("SansSerif", 0, 12));
        textQuantidade.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        textQuantidade.setPreferredSize(new java.awt.Dimension(10, 26));
        textQuantidade.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                textQuantidadeFocusLost(evt);
            }
        });

        lbUnidade.setFont(new java.awt.Font("SansSerif", 0, 12));
        lbUnidade.setText("Unidade");

        cbUnidade.setBackground(java.awt.Color.white);
        cbUnidade.setFont(new java.awt.Font("SansSerif", 0, 12));
        cbUnidade.setEnabled(false);
        cbUnidade.setPreferredSize(new java.awt.Dimension(35, 26));
        cbUnidade.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbUnidadeActionPerformed(evt);
            }
        });

        lbValUnit.setFont(new java.awt.Font("SansSerif", 0, 12));
        lbValUnit.setText("Valor Unitário");

        textValUnit.setBackground(java.awt.Color.white);
        textValUnit.setEditable(false);
        textValUnit.setFont(new java.awt.Font("SansSerif", 0, 12));
        textValUnit.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        textValUnit.setPreferredSize(new java.awt.Dimension(10, 26));
        textValUnit.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                textValUnitFocusLost(evt);
            }
        });

        lbFatorConversao.setFont(new java.awt.Font("SansSerif", 0, 12));
        lbFatorConversao.setText("Fator Conversão");

        textFatorConv.setBackground(java.awt.Color.white);
        textFatorConv.setEditable(false);
        textFatorConv.setFont(new java.awt.Font("SansSerif", 0, 12));
        textFatorConv.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        textFatorConv.setPreferredSize(new java.awt.Dimension(10, 26));

        lbValTotal.setFont(new java.awt.Font("SansSerif", 0, 12));
        lbValTotal.setText("Valor Total");

        textValorTotal.setBackground(java.awt.Color.white);
        textValorTotal.setEditable(false);
        textValorTotal.setFont(new java.awt.Font("SansSerif", 0, 12));
        textValorTotal.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        textValorTotal.setPreferredSize(new java.awt.Dimension(10, 26));

        panelBotao.setBorder(javax.swing.BorderFactory.createEtchedBorder(null, java.awt.Color.gray));
        panelBotao.setFont(new java.awt.Font("DejaVu Sans", 0, 12));

        btnConfirmar.setFont(new java.awt.Font("SansSerif", 0, 12)); // NOI18N
        btnConfirmar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/ok.png"))); // NOI18N
        btnConfirmar.setText("Confirmar");
        btnConfirmar.setEnabled(false);
        btnConfirmar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnConfirmarMouseClicked(evt);
            }
        });

        btnCancelar.setFont(new java.awt.Font("SansSerif", 0, 12));
        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/cancel.png"))); // NOI18N
        btnCancelar.setText("Cancelar");
        btnCancelar.setToolTipText("Cancelar");
        btnCancelar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnCancelarMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout panelBotaoLayout = new javax.swing.GroupLayout(panelBotao);
        panelBotao.setLayout(panelBotaoLayout);
        panelBotaoLayout.setHorizontalGroup(
            panelBotaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelBotaoLayout.createSequentialGroup()
                .addGap(144, 144, 144)
                .addComponent(btnConfirmar, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(162, Short.MAX_VALUE))
        );

        panelBotaoLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnCancelar, btnConfirmar});

        panelBotaoLayout.setVerticalGroup(
            panelBotaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelBotaoLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelBotaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE, false)
                    .addComponent(btnConfirmar)
                    .addComponent(btnCancelar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        panelBotaoLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btnCancelar, btnConfirmar});

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lbDescricao)
                    .addComponent(lbCodigo)
                    .addComponent(lbValUnit)
                    .addComponent(lbQuantidade))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(textCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(textQuantidade, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(textValUnit, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lbValTotal)
                            .addComponent(lbUnidade))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(cbUnidade, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(lbFatorConversao)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(textFatorConv, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(textValorTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(textDescricao, javax.swing.GroupLayout.PREFERRED_SIZE, 463, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(panelBotao, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(9, 9, 9))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbCodigo)
                    .addComponent(textCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbDescricao)
                    .addComponent(textDescricao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbQuantidade)
                    .addComponent(lbUnidade)
                    .addComponent(lbFatorConversao)
                    .addComponent(textFatorConv, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(textQuantidade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cbUnidade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbValUnit)
                    .addComponent(textValUnit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lbValTotal)
                    .addComponent(textValorTotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(panelBotao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-584)/2, (screenSize.height-262)/2, 584, 262);
    }// </editor-fold>//GEN-END:initComponents

    //<editor-fold defaultstate="collapsed" desc="Events">
    private void textCodigoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textCodigoKeyPressed
        if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_F3 &&
                                                       textCodigo.isEditable()){
            FormProduto form = new FormProduto(FormProduto.K_FORM_PESQUISA);
            form.setModal(true);
            form.setVisible(true);

            this.produto = new Produto();
            this.produto = form.getProduto();

            if(this.produto != null){
                showProduto();
                btnConfirmar.setEnabled(true);
            }
            else{
                btnConfirmar.setEnabled(false);
            }
        }
    }//GEN-LAST:event_textCodigoKeyPressed

    private void textCodigoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_textCodigoFocusLost
        try{
            if(textCodigo.getText().length() > 0 && textCodigo.isEditable()){
                this.produto = new Produto();
                this.produto =
                   this.produto.refresh(Integer.parseInt(textCodigo.getText()));

                if(this.produto != null){
                    showProduto();
                    btnConfirmar.setEnabled(true);
                }
                else{
                    btnConfirmar.setEnabled(false);
                }
            }
        }
        catch(Exception ex){
            showMessageError(ErrorMessage.MSG_GERAL_FORMAT, "Item");
        }
    }//GEN-LAST:event_textCodigoFocusLost

    private void textQuantidadeFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_textQuantidadeFocusLost
        try{
            if(textQuantidade.isEditable()
                                      && textQuantidade.getText().length() > 0){
                textQuantidade.setText(
                      df.format(Double.parseDouble(textQuantidade.getText())).
                                replace(",", "."));

                if(textValUnit.getText().length() > 0){
                    textValorTotal.setText(
                           df.format(Double.parseDouble(textValUnit.getText()) *
                           Double.parseDouble(textQuantidade.getText())).
                                                             replace(',', '.'));
                }
            }
        }
        catch(Exception ex){
            textValorTotal.setText("0.00");
            textQuantidade.setText("0.00");
            showMessageError(ErrorMessage.MSG_GERAL_FORMAT, "Item");
        }
    }//GEN-LAST:event_textQuantidadeFocusLost

    private void textValUnitFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_textValUnitFocusLost
        try{
            if(textValUnit.getText().length() > 0 && textValUnit.isEditable()){
                textValUnit.setText(
                      df.format(Double.parseDouble(textValUnit.getText())).
                                replace(",", "."));

                if(textQuantidade.getText().length() > 0){
                    textValorTotal.setText(
                        df.format(Double.parseDouble(textValUnit.getText()) *
                        Double.parseDouble(textQuantidade.getText())).
                                                             replace(',', '.'));
                }
            }
        }
        catch(Exception ex){
            textValorTotal.setText("0.00");
            textValUnit.setText("0.00");
            showMessageError(ErrorMessage.MSG_GERAL_FORMAT, "Item");
        }
    }//GEN-LAST:event_textValUnitFocusLost
    // Fecha o formulario
    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        this.dispose();
    }//GEN-LAST:event_formWindowClosed
    // Fecha o formulario
    private void btnCancelarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnCancelarMouseClicked
        this.dispose();
    }//GEN-LAST:event_btnCancelarMouseClicked

    private void cbUnidadeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbUnidadeActionPerformed
        if(cbUnidade.getSelectedIndex() > 0){
            textFatorConv.setText(
                    df.format(produto.getFatorConversao()).replace(",", "."));
        }
        else{
            textFatorConv.setText("1.00");
        }
    }//GEN-LAST:event_cbUnidadeActionPerformed
    // Insere ou atualiza um novo item
    private void btnConfirmarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnConfirmarMouseClicked
        try{
            if(mapearItem() && btnConfirmar.isEnabled()){
                boolean flag = true;
                if(item.isNew()){
                    flag = situacao == K_FORM_ORCAMENTO ?
                            item.insert(Item.K_ITEM_ORCAMENTO) :
                            item.insert(Item.K_ITEM_NOTA);
                }
                else{
                    flag = situacao == K_FORM_ORCAMENTO ?
                            item.update(Item.K_ITEM_ORCAMENTO) :
                            item.update(Item.K_ITEM_NOTA);
                }

                if(flag){
                    this.dispose();
                }
            }
        }
        catch(Exception ex){
            ex.printStackTrace();
        }
    }//GEN-LAST:event_btnConfirmarMouseClicked
    //</editor-fold>

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnConfirmar;
    private javax.swing.JComboBox cbUnidade;
    private javax.swing.JLabel lbCodigo;
    private javax.swing.JLabel lbDescricao;
    private javax.swing.JLabel lbFatorConversao;
    private javax.swing.JLabel lbQuantidade;
    private javax.swing.JLabel lbUnidade;
    private javax.swing.JLabel lbValTotal;
    private javax.swing.JLabel lbValUnit;
    private javax.swing.JPanel panelBotao;
    private javax.swing.JTextField textCodigo;
    private javax.swing.JTextField textDescricao;
    private javax.swing.JTextField textFatorConv;
    private javax.swing.JTextField textQuantidade;
    private javax.swing.JTextField textValUnit;
    private javax.swing.JTextField textValorTotal;
    // End of variables declaration//GEN-END:variables

    //<editor-fold defaultstate="collapsed" desc="Methods">
    private void showMessageError(String msg, String title){
        JOptionPane.showMessageDialog(this, msg, title,
                                                    JOptionPane.ERROR_MESSAGE);
    }

    private Boolean mapearItem(){
        Boolean valid = true;
        try{
            item.setQuantidade(Double.parseDouble(textQuantidade.getText()));
            item.setValorUnitario(Double.parseDouble(textValUnit.getText()));
            item.setFatorConv(Double.parseDouble(textFatorConv.getText()));
            item.setIdProduto(produto.getCod_objeto());
            item.setUnidCompra((String)cbUnidade.getSelectedItem());
        }
        catch(Exception ex){
            ex.printStackTrace();
            valid = true;
        }
        return valid;
    }

    // Inicializa os componentes de acordo com o objeto recebido
    private void initializeMyComponents(){
        enableFields();
        showItem();
    }

    // Habilita os campos para edicao
    private void enableFields(){
        if(modo != K_FORM_EXIBICAO){
            if(item.isNew()){
                textCodigo.setEditable(true);
                textQuantidade.setEditable(true);
                textValUnit.setEditable(true);
                cbUnidade.setEnabled(true);
            }
            else{
                textCodigo.setEditable(true);
                textQuantidade.setEditable(true);
                textValUnit.setEditable(true);
                cbUnidade.setEnabled(true);
                textCodigo.setText("");
                textQuantidade.setText("");
                textValUnit.setText("");
                textValorTotal.setText("");
                textDescricao.setText("");
                textFatorConv.setText("");
            }
        }
        else{
            textCodigo.setEditable(false);
            textDescricao.setEditable(false);
            textQuantidade.setEditable(false);
            textFatorConv.setEditable(false);
            textValUnit.setEditable(false);
            cbUnidade.setEnabled(false);
            btnConfirmar.setEnabled(false);
        }
    }

    // Exibe o item corrente
    private void showItem(){

        if(!item.isNew()){
            this.produto = new Produto();
            this.produto = this.produto.refresh(item.getIdProduto());
            showProduto();
//            textCodigo.setText(this.produto.getCodProd().toString());
            textQuantidade.setText(
                             df.format(item.getQuantidade()).replace(',', '.'));
            textValUnit.setText(
                          df.format(item.getValorUnitario()).replace(',', '.'));
            textValorTotal.setText(
                 df.format(item.getValorUnitario() * item.getQuantidade()).
                                                            replace(',', '.'));
//            textDescricao.setText(this.produto.getDescricao());
            textFatorConv.setText(df.format(
                                        item.getFatorConv()).replace(",","."));
            selectedIndex();
        }
        else{
            textCodigo.setText("");
            textQuantidade.setText("");
            textValUnit.setText("");
            textValorTotal.setText("");
            textDescricao.setText("");
            textFatorConv.setText("1.00");
        }
    }

    // Exibe o produto recuperado
    private void showProduto(){
        textCodigo.setText(produto.getCodProd().toString());
        textDescricao.setText(produto.getDescricao());
        textFatorConv.setText(
                      df.format(produto.getFatorConversao()).replace(',', '.'));
        mountCombo();
    }

    // Monta o combo box com as unidades do produto
    private void mountCombo(){
        cbUnidade.removeAllItems();

        Unidade un = new Unidade();
        un = un.refresh(produto.getIdUnidade1());
        cbUnidade.addItem(un.getUnidade());

        un = un.refresh(produto.getIdUnidade2());
        cbUnidade.addItem(un.getUnidade());
        cbUnidade.setSelectedIndex(0);
    }

    // Seleciona a posicao no combo caso o item ja exista
    private void selectedIndex(){
        int index = 0;

        for(int i = 0; i < cbUnidade.getItemCount(); i++){
            if(item.getUnidCompra().equals(cbUnidade.getItemAt(i))){
                index = i;
            }
        }

        cbUnidade.setSelectedIndex(index);
    }
    //</editor-fold>
}
